import { ComponentInfoType, ComponentStateType } from '.'

export function getNextSelectedId(fe_id: string, componentList: ComponentInfoType[]) {
  const visibleComponentList = componentList.filter(c => !c.isHidden)
  const index = visibleComponentList.findIndex(c => c.fe_id === fe_id)

  if (index < 0) return ''

  // 重新计算 selectedId
  let newSelectedId = ''
  const { length } = visibleComponentList
  if (length <= 1) {
    newSelectedId = ''
  } else {
    if (index + 1 === length) {
      newSelectedId = visibleComponentList[index - 1].fe_id
    } else {
      newSelectedId = visibleComponentList[index + 1].fe_id
    }
  }

  return newSelectedId
}

/**
 * 插入新组件
 * @param state
 * @param newComponent
 */
export function insertNewComponent(
  state: ComponentStateType,
  newComponent: ComponentInfoType | null
): ComponentInfoType[] {
  const { selectedId, componentList } = state

  const newComponentList = componentList.slice()
  const selectedComponentIndex = componentList.findIndex(c => c.fe_id === selectedId)

  if (newComponent) {
    if (selectedComponentIndex >= 0) {
      newComponentList.splice(selectedComponentIndex + 1, 0, newComponent)
    } else {
      newComponentList.push(newComponent)
    }
  }

  return newComponentList
}
